package com.taa.middleware.threadpool.registry.redis;

import com.taa.middleware.threadpool.domain.model.entity.ThreadPoolConfigEntity;
import com.taa.middleware.threadpool.domain.model.valobj.RegistryEnumVO;
import com.taa.middleware.threadpool.registry.IRegistry;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;

import java.time.Duration;
import java.util.List;

/**
 * @author: taa
 * @Desc: Redis注册中心实现
 * @create: 2024-10-14 19:07
 **/
public class RedisRegistry implements IRegistry {
    private final RedissonClient redissonClient;

    public RedisRegistry(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 注册线程池信息
     * @param threadPoolEntities
     */
    @Override
    public void reportThreadPool(List<ThreadPoolConfigEntity> threadPoolEntities) {
        RList<ThreadPoolConfigEntity> list = redissonClient
                .getList(RegistryEnumVO.THREAD_POOL_CONFIG_LIST_KEY.getKey());
        list.clear();
        list.addAll(threadPoolEntities);
    }

    /**
     * 注册线程池配置
     * @param threadPoolConfigEntity
     */
    @Override
    public void reportThreadPoolConfigParameter(ThreadPoolConfigEntity threadPoolConfigEntity) {
        String cacheKey = RegistryEnumVO.THREAD_POOL_CONFIG_LIST_KEY.getKey() + "_"
                + threadPoolConfigEntity.getAppName() + "_"
                + threadPoolConfigEntity.getThreadPoolName();

        RBucket<ThreadPoolConfigEntity> bucket = redissonClient.getBucket(cacheKey);
        //有效期为30天，如果没有更新或读取操作，30天后该条目将自动从Redis中删除。
        bucket.set(threadPoolConfigEntity, Duration.ofDays(30));
    }
}

